package com.ktjiaoyu.crm.web.controller;

import com.ktjiaoyu.crm.entity.Right;
import com.ktjiaoyu.crm.entity.Role;
import com.ktjiaoyu.crm.service.IRoleService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author lee
 */
@Controller
public class RoleController {
    @Resource
    private IRoleService roleService;

    @RequestMapping("/role/list")
    public String list(Model model, String roleName,
                       @RequestParam(required = false, defaultValue = "1") int pageIndex){
        Sort sort = new Sort(Sort.Direction.ASC, "roleId");
        Pageable pageable = PageRequest.of(pageIndex-1, 3, sort);
        Page<Role> rolePage = roleService.findRoles(roleName, pageable);
        model.addAttribute("rolePage", rolePage);
        model.addAttribute("roleName", roleName);

        return "role/list";
    }

    @RequestMapping("/role/add")
    public String add(Model model){
        //查询所有权限
        List<Right> rights = roleService.findAllRights();
        model.addAttribute("rights", rights);
        return "role/add";
    }

    @RequestMapping("/role/save")
    public String save(Role role, String[] rightCodes){
        //选中的权限添加到角色对象中
        if(rightCodes!=null){
            for (String rightCode : rightCodes){
                Right right = new Right();
                right.setRightCode(rightCode);
                role.getRights().add(right);
            }
        }
        //保存角色数据级联新增权限数据
        roleService.saveRole(role);
        return "redirect:/role/list";
    }

    @RequestMapping(value = "/role/edit")
    public String edit(Long roleId, Model model){
        //查询角色信息
        Role role = roleService.getRole(roleId);
        model.addAttribute("role", role);

        //查询角色所拥有的权限
        List<Right> roleRights = roleService.findRightsByRole(role);
        model.addAttribute("roleRights", roleRights);

        //查询所有权限
        List<Right> rights = roleService.findAllRights();
        model.addAttribute("rights", rights);

        return "role/edit";
    }

    @RequestMapping(value = "/role/del")
    @ResponseBody
    public Map del(Long roleId){

        Map map = new HashMap();
        try{
            this.roleService.delRole(roleId);
            map.put("delResult", "true");
        }catch (Exception e){
            map.put("delResult", "false");
        }
        return map;
    }

}
